package com.ruoyi.web.util;

import com.ruoyi.web.common.BusinessException;
import org.apache.commons.lang3.math.NumberUtils;

import java.math.BigDecimal;

/**
 * <br>
 *
 * @author chenwujie
 * @date 2021/2/13
 */
public class BigDecimalCheckUtils {

    public static void isNumberAndGeZero(String typeName, String amount, int maxDigits) {
        if (!NumberUtils.isCreatable(amount)) {
            throw new BusinessException("请检查输入的{0}:{1}", typeName, amount);
        }
        BigDecimal amountBigDecimal = new BigDecimal(amount);
        if (getNumberOfDecimalPlaces(amountBigDecimal) > maxDigits) {
            throw new BusinessException("{0}最多精确{1}位，输入值：{2}", typeName, maxDigits, amount);
        }
        if (amountBigDecimal.compareTo(BigDecimal.ZERO) < 0) {
            throw new BusinessException("输入的{0}需大于等于零：{1}", typeName, amount);
        }
    }

    public static int getNumberOfDecimalPlaces(BigDecimal bigDecimal) {
        String string = bigDecimal.stripTrailingZeros().toPlainString();
        int index = string.indexOf(".");
        return index < 0 ? 0 : string.length() - index - 1;
    }

    public static boolean isZero(BigDecimal value){
        return BigDecimal.ZERO.compareTo(value) == 0;
    }
}
